<?php

class SJB_Payment_ShoppingCart extends SJB_Function
{
	public function execute()
	{
		$tp = SJB_System::getTemplateProcessor();
		$currentUser = SJB_UserManager::getCurrentUser();
		$action = SJB_Request::getVar('action', false);
		$error = SJB_Request::getVar('error', false);
		$applyPromoCode = SJB_Request::getVar('applyPromoCode', false);
		$action = $applyPromoCode?'applyPromoCode':$action;
		$numberOfListings = SJB_Request::getVar('number_of_listings');
		$productInfo = null;
		$errors = array();
		switch ($action) {
			case 'delete':
				$itemSID = SJB_Request::getVar('item_sid', 0, false, 'int');
				if (SJB_UserManager::isUserLoggedIn())
					SJB_ShoppingCart::deleteItemFromCartBySID($itemSID, $currentUser->getSID());
				else {
					$products = SJB_Session::getValue('products');
					if (!empty($products[$itemSID])) {
						unset($products[$itemSID]);
						SJB_Session::setValue('products', $products);
					}
				}
				break;
			case 'checkout':
				if (SJB_UserManager::isUserLoggedIn()) {
					$products = SJB_Session::getValue('products');
					$products = $products?$products:array();
					$trialProduct = false;
					foreach ($products as $product) {
						if (!empty($product['product_info'])) {
							$productInfo = unserialize($product['product_info']);
							if ($currentUser->getUserGroupSID() != $productInfo['user_group_sid']) {
								SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . "/shopping-cart/?error=user_group");
							}
							elseif (in_array($productInfo['sid'], $currentUser->getTrialProductSIDByUserSID())) {
								$trialProduct = true;
							}
							else {
								$product = new SJB_Product($productInfo, $productInfo['product_type']);
								$number_of_listings = !empty($productInfo['number_of_listings'])?$productInfo['number_of_listings']:1;
								$product->setNumberOfListings($number_of_listings);
								$productInfo['price'] = $product->getPrice();
								SJB_ShoppingCart::addToShoppingCart($productInfo, $currentUser->getSID());
							}
						}
					}
					SJB_Session::unsetValue('products');
					if ($trialProduct)
						SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . "/shopping-cart/?error=trial_product");
					elseif ($products)
						SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . "/shopping-cart/");
					$products = SJB_ShoppingCart::getAllProductsByUserSID($currentUser->getSID());
					$isRecurring = false;
					$sub_total = 0;
					foreach ($products as $key => $product) {
						$productInfo = unserialize($product['product_info']);
						if (!empty($productInfo['recurring']))
							$isRecurring = true;

						if (!empty($productInfo['pricing_type']) == 'volume_based' && isset($numberOfListings[$productInfo['sid']][$product['sid']])) {
							$productInfo['number_of_listings'] = $numberOfListings[$productInfo['sid']][$product['sid']];
							$productObj = new SJB_Product($productInfo, $productInfo['product_type']);
							$number_of_listings = !empty($productInfo['number_of_listings'])?$productInfo['number_of_listings']:1;
							$productObj->setNumberOfListings($number_of_listings);
							$productInfo['price'] = $productObj->getPrice();
							if (!empty($productInfo['code_info'])) {
								foreach ($productInfo['code_info'] as $codeInfo) {
									switch ($codeInfo['type']) {
										case 'percentage':
											$productInfo['price'] = round($productInfo['price'] - ($productInfo['price']/100)*$codeInfo['discount'], 2);
											break;
										case 'fixed':
											$productInfo['price'] = round($productInfo['price'] - $codeInfo['discount'], 2);
											break;
									}
								}
							}

							SJB_ShoppingCart::updateItemBySID($product['sid'], $productInfo);
						}
						if ($productInfo['price'] <= 0) {
							$listingNumber = !empty($productInfo['number_of_listings']) ? $productInfo['number_of_listings'] : null;
							$contract = new SJB_Contract(array('product_sid' => $productInfo['sid'], 'numberOfListings' => $listingNumber));
							$contract->setUserSID($currentUser->getSID());
							$contract->setPrice(0);
							if ($contract->saveInDB()) {
								if ($productInfo['product_type'] == 'banners' && !empty($productInfo['banner_info'])) {
									$bannersObj = new SJB_Banners();
									$bannerInfo = $productInfo['banner_info'];
									$bannersObj->addBanner($bannerInfo['title'], $bannerInfo['link'], $bannerInfo['bannerFilePath'], $bannerInfo['sx'], $bannerInfo['sy'], $bannerInfo['type'], 0, $bannerInfo['banner_group_sid'], $bannerInfo, $currentUser->getSID(), $contract->getID());
									$bannerGroup = $bannersObj->getBannerGroupBySID($bannerInfo['banner_group_sid']);
									SJB_AdminNotifications::sendAdminBannerAddedLetter($currentUser->getSID(), $bannerGroup);
								}
								if ($contract->isFeaturedProfile())
									SJB_UserManager::makeFeaturedBySID($currentUser->getSID());
								if (SJB_UserNotificationsManager::isUserNotifiedOnSubscriptionActivation($currentUser->getSID()))
									SJB_Notifications::sendSubscriptionActivationLetter($currentUser->getSID(), $productInfo);
							}
							unset($products[$key]);
							SJB_ShoppingCart::deleteItemFromCartBySID($product['sid'], $currentUser->getSID());
							SJB_Statistics::addStatistics('payment', 'product', $product['sid'], false, 0, 0, $currentUser->getSID(), 0);
						}
						else {
							$sub_total += $productInfo['price'];
							$products[$key] = $productInfo;
							$products[$key]['item_sid'] = $product['sid'];
							$products[$key]['product_info'] = serialize($productInfo);
						}
					}

					$codeInfo = array();
					$index = 1;
					$items = array();
					foreach ($products as $product) {
						$product_info = unserialize($product['product_info']);
						if (!empty($product['code_info'])) {
							foreach ($product['code_info'] as $productCodeInfo) {
								$codeInfo[$productCodeInfo['sid']][] = $product['sid'];
							}
						}
						$qty = !empty($product_info['number_of_listings'])?$product_info['number_of_listings']:null;
						$items['products'][$index] = $product_info['sid'];
						if ($qty > 0)
							$items['price'][$index] = round($product['price']/ $qty, 2);
						else
							$items['price'][$index] = round($product['price'], 2);
						$items['amount'][$index] = $product['price'];
						$items['custom_item'][$index] = "";
						$items['qty'][$index] = $qty;
						$items['custom_info'][$index]['shoppingCartRecord'] = $product['item_sid'];
						if ($product_info['product_type'] == 'banners' && !empty($product_info['banner_info']))
							$items['custom_info'][$index]['banner_info'] = $product_info['banner_info'];
						$index++;
					}
					if ($sub_total <= 0) {
						foreach ($products as $product) {
							$listingNumber = !empty($product['number_of_listings']) ? $product['number_of_listings'] : null;
							$contract = new SJB_Contract(array('product_sid' => $product['sid'], 'numberOfListings' => $listingNumber));
							$contract->setUserSID($currentUser->getSID());
							$contract->setPrice(0);
							if ($contract->saveInDB()) {
								if ($product['product_type'] == 'banners' && !empty($product['banner_info'])) {
									$bannersObj = new SJB_Banners();
									$bannerInfo = $product['banner_info'];
									$bannersObj->addBanner($bannerInfo['title'], $bannerInfo['link'], $bannerInfo['bannerFilePath'], $bannerInfo['sx'], $bannerInfo['sy'], $bannerInfo['type'], 0, $bannerInfo['banner_group_sid'], $bannerInfo, $currentUser->getSID(), $contract->getID());
									$bannerGroup = $bannersObj->getBannerGroupBySID($bannerInfo['banner_group_sid']);
									SJB_AdminNotifications::sendAdminBannerAddedLetter($currentUser->getSID(), $bannerGroup);
								}
								if ($contract->isFeaturedProfile()) {
									SJB_UserManager::makeFeaturedBySID($currentUser->getSID());
								}
								if (SJB_UserNotificationsManager::isUserNotifiedOnSubscriptionActivation($currentUser->getSID())) {
									SJB_Notifications::sendSubscriptionActivationLetter($currentUser->getSID(), $product);
								}
								SJB_Statistics::addStatistics('payment', 'product', $product['sid'], false, 0, 0, $currentUser->getSID(), 0);
							}
						}
						SJB_ShoppingCart::deleteItemsFromCartByUserSID($currentUser->getSID());
						$userGroupInfo = SJB_UserGroupManager::getUserGroupInfoBySID($currentUser->getUserGroupSID());
						$pageId = !empty($userGroupInfo['after_registration_redirect_to']) ? $userGroupInfo['after_registration_redirect_to'] : '';
						$redirectUrl = SJB_UserGroupManager::getRedirectUrlByPageID($pageId);
						if($redirectUrl) {
							SJB_HelperFunctions::redirect($redirectUrl);
						} else {
							SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . "/my-products/");
						}
					}
					else {
						$subuserInfo = $currentUser->getSubuserInfo();
						$user_sid = isset($subuserInfo['sid']) ? $subuserInfo['sid'] : $currentUser->getSID();
						$tax_info = SJB_TaxesManager::getTaxInfoByUserSidAndPrice($user_sid, $sub_total);
						$tp->assign("tax", $tax_info);
						$totalPrice = SJB_InvoiceManager::getTotalPrice($sub_total, $tax_info['tax_amount'], $tax_info['price_includes_tax']);
						if ($isRecurring) {
							$tp->assign('confirmation', 1);
							$tp->assign("sub_total_price", $sub_total);
							$tp->assign("totalPrice", $totalPrice);
						} else {
							$invoice_info = array(
								'user_sid' => $user_sid,
								'include_tax' => !empty($tax_info['sid']) ? 1 : 0,
								'total' => $totalPrice,
								'sub_total' => $sub_total,
								'success_page_url' => SJB_System::getSystemSettings('SITE_URL') . "/create-contract/",
								'status' => SJB_Invoice::INVOICE_STATUS_UNPAID,
								'tax_info' => $tax_info,
								'items' => $items,
								'is_recurring' => false,
							);
							$invoice_sid = SJB_InvoiceManager::generateInvoice($invoice_info);
							SJB_PromotionsManager::addCodeToHistory($codeInfo, $invoice_sid, $user_sid);
							SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . "/payment-page/?invoice_sid=" . $invoice_sid);
						}
					}
				}
				break;
			case 'applyPromoCode':
				$promotionCode = SJB_Request::getVar('promotion_code', false);
				if ($promotionCode) {
					if (SJB_UserManager::isUserLoggedIn())
						$products = SJB_ShoppingCart::getAllProductsByUserSID($currentUser->getSID());
					else {
						$products = SJB_Session::getValue('products');
						$products = $products?$products:array();
						krsort($products);
					}
					$allowShoppingItems = array();
					$productSIDs = array();
					foreach ($products as $product) {
						$productInfo = unserialize($product['product_info']);
						if (!isset($productInfo['code_info'])) {
							$allowShoppingItems[] = $product ['sid'];
							$productSIDs[] = $productInfo['sid'];
						}
						else {
							$alreadyUse = false;
							foreach ($productInfo['code_info'] as $code_info) {
								if ($code_info['code'] == $promotionCode)
									$alreadyUse = true;
							}
							if (!$alreadyUse) {
								$allowShoppingItems[] = $product['sid'];
								$productSIDs[] = $productInfo['sid'];
							}
						}
					}
					if ($codeInfo = SJB_PromotionsManager::checkCode($promotionCode, $productSIDs)) {
						$productSIDs = $codeInfo['product_sid']?explode(',', $codeInfo['product_sid']):false;
						$appliedProducts = array();
						$codeValid = false;
						foreach ($products as $key => $product) {
							$productInfo = unserialize($product['product_info']);
							if ((!$productSIDs || in_array($productInfo['sid'], $productSIDs)) && $allowShoppingItems && in_array($product['sid'], $allowShoppingItems)) {
								if (isset($numberOfListings[$productInfo['sid']][$product['sid']]) && isset($productInfo['number_of_listings'])) {
									$productInfo['number_of_listings'] = $numberOfListings[$productInfo['sid']][$product['sid']];
								}
								$codeValid = true;
								if (!empty($codeInfo['type'])) {
									$sub_total = 0;
									switch ($codeInfo['type']) {
										case 'percentage':
											$sub_total = round($productInfo['price'] - ($productInfo['price']/100)*$codeInfo['discount'], 2);
											break;
										case 'fixed':
											$sub_total = round($productInfo['price'] - $codeInfo['discount'], 2);
											break;
									}
									$productInfo['price'] = $sub_total<0?0:$sub_total;
								}
								$productInfo['code_info'][] = $codeInfo;
								$appliedProducts[] = $productInfo;
								if (SJB_UserManager::isUserLoggedIn()) {
									SJB_ShoppingCart::updateItemBySID($product['sid'], $productInfo);
								} else {
									$products[$key]['product_info'] = serialize($productInfo);
									SJB_Session::setValue('products', $products);
								}
							}
						}
						if (!$codeValid)
							$errors['NOT_VALID'] = 'Invalid promotion code';

						$tp->assign('applied_products', $appliedProducts);
						$tp->assign('code_info', $codeInfo);
					}
					else {
						$errors['NOT_VALID'] = 'Invalid promotion code';
					}
				}
				else
					$errors['EMPTY_VALUE'] = 'Promotion code';
				break;
		}
		if (SJB_UserManager::isUserLoggedIn())
			$products = SJB_ShoppingCart::getAllProductsByUserSID($currentUser->getSID());
		else {
			$products = SJB_Session::getValue('products');
			$products = $products?$products:array();
			krsort($products);
		}

		$totalPrice = 0;
		foreach ($products as $key => $product) {
			$productInfo = unserialize($product['product_info']);
			if (!empty($productInfo['expiration_period']) && !is_numeric($productInfo['expiration_period']))
				$productInfo['period'] = ucwords($productInfo['expiration_period']);
			elseif (!empty($productInfo['pricing_type']) && $productInfo['pricing_type'] == 'volume_based') {
				$volumeBasedPricing = $productInfo['volume_based_pricing'];
				$productObj = new SJB_Product($productInfo, $productInfo['product_type']);
				$number_of_listings = !empty($productInfo['number_of_listings'])?$productInfo['number_of_listings']:1;
				$productObj->setNumberOfListings($number_of_listings);
				$productInfo['price'] = $productObj->getPrice();
				if (!empty($productInfo['code_info'])) {
					foreach ($productInfo['code_info'] as $codeInfo) {
						switch ($codeInfo['type']) {
							case 'percentage':
								$productInfo['price'] = round($productInfo['price'] - ($productInfo['price']/100)*$codeInfo['discount'], 2);
								break;
							case 'fixed':
								$productInfo['price'] = round($productInfo['price'] - $codeInfo['discount'], 2);
								break;
						}
					}
				}
				$productInfo['price'] = $productInfo['price']<0?0:$productInfo['price'];
				$minListings = min($volumeBasedPricing['listings_range_from']);
				$maxListings = max($volumeBasedPricing['listings_range_to']);
				$countListings = array();
				for ($i = $minListings; $i <= $maxListings; $i++) {
					$countListings[$i]['number_of_listings'] = $i;
					for ($j = 1; $j <= count($volumeBasedPricing['listings_range_from']); $j++) {
						if ($i >= $volumeBasedPricing['listings_range_from'][$j] && $i <= $volumeBasedPricing['listings_range_to'][$j]) {
							$countListings[$i]['price'] = $volumeBasedPricing['price_per_unit'][$j]*$i;
							if (!empty($productInfo['code_info'])) {
								foreach ($productInfo['code_info'] as $codeInfo) {
									switch ($codeInfo['type']) {
										case 'percentage':
											$countListings[$i]['price'] = round($countListings[$i]['price'] - ($countListings[$i]['price']/100)*$codeInfo['discount'], 2);
											break;
										case 'fixed':
											$countListings[$i]['price']= round($countListings[$i]['price'] - $codeInfo['discount'], 2);
											break;
									}
								}
							}
						}
					}
				}
				$productInfo['price'] = $productInfo['price'] < 0 ? 0 : $productInfo['price'];
				$productInfo['count_listings'] = $countListings;
			}
			elseif (!empty($productInfo['pricing_type']) && $productInfo['pricing_type'] == 'fixed') {
				unset($productInfo['volume_based_pricing']);
			}
			if (empty($productInfo['volume_based_pricing'])){
				$totalPrice += (float)$productInfo['price'];
			}
			$products[$key] = $productInfo;
			$products[$key]['item_sid'] = $product['sid'];
		}
		if ($currentUser){
			$tax_info = SJB_TaxesManager::getTaxInfoByUserSidAndPrice($currentUser->getSID(), $totalPrice);
			$tp->assign("tax", $tax_info);
		}

		$userGroupID = $productInfo ? SJB_UserGroupDBManager::getUserGroupIDBySID($productInfo['user_group_sid']) : false;
		$tp->assign("error", $error);
		$tp->assign("errors", $errors);
		$tp->assign("total_price", $totalPrice);
		$tp->assign('products', $products);
		$tp->assign('userGroupID', $userGroupID);
		$tp->display('shopping_cart.tpl');
	}
}